const path = require('path')
const http = require('http')
const CompressionPlugin = require('compression-webpack-plugin')
const productionGzipExtensions = /\.(js|css|json|txt|html|ico|svg)(\?.*)?$/i
let pages = {}
pages['index'] = {
  entry: `src/pages/main.js`,
  template: `src/pages/index.html`,
  filename: `index.html`,
  chunks: ['chunk-vendors', 'chunk-common', `index`],
}
const keepAliveAgent = new http.Agent({ keepAlive: true })
const proxyTarget = 'http://localhost:9000'
const proxyInterfaces = ['api']
const proxy = {}
for (let item of proxyInterfaces) {
  let pathRewrite = {}
  pathRewrite[`^/${item}`] = `/${item}`
  proxy[item] = {
    target: proxyTarget,
    changeOrigin: true,
    pathRewrite: pathRewrite,
    agent: keepAliveAgent,
  }
}
module.exports = {
  pages,
  productionSourceMap: false,
  publicPath: process.env.NODE_ENV === 'production' ? '/report' : '/',
  runtimeCompiler: false,
  configureWebpack: {
    plugins: [],
  },
  // transpileDependencies: ['element-ui', 'v-contextmenu', 'vue-runtime-helpers'],
  chainWebpack: config => {
    config.plugins.delete('prefetch-index').delete('preload-index')
    config.plugin('define').tap(args => {
      let globalVars = args[0]
      let feConfig = require(path.resolve('.', './src/feConfig/' + (process.env.VUE_APP_ENV || 'development')))
      globalVars.feConfig = JSON.stringify(feConfig)
      return args
    })
    config.entry('polyfill').add('@babel/polyfill')
    const imagesRule = config.module.rule('images')
    imagesRule.uses.clear()
    imagesRule
      .use('file-loader')
      .loader('url-loader')
      .options({
        limit: 10000,
        fallback: {
          loader: 'file-loader',
          options: {
            name: 'img/[name].[ext]',
          },
        },
      })
    config.optimization.splitChunks({
      cacheGroups: {
        vendors: {
          name: 'chunk-vendors',
          // minChunks: pageArray.length,
          minChunks: 1,
          test: /[\\/]node_modules[\\/]/,
          priority: -10,
          chunks: 'initial',
        },
      },
    })
    if (process.env.NODE_ENV === 'production') {
      config.plugin('compressionPlugin')
        .use(new CompressionPlugin({
          filename: '[path][base].gz',
          algorithm: 'gzip',
          test: productionGzipExtensions,
          threshold: 10240,
          minRatio: 0.8,
          deleteOriginalAssets: false,
        }))
    }
  },
  devServer: {
    // host: 'dev.sense.com',
    proxy,
  },
}
